/* Copyright 2008 Milko Slavov
 * This file is part of GEH.
 * GEH is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * GEH is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * See <http://www.gnu.org/licenses/>.
*/

package com.geh.event;

import java.util.LinkedList;

/**
 * Synchronized FIFO queue used by ThreadPool
 * 
 * @author mslavov
 *
 */

class SynchronizedQueue {
	
	private LinkedList queue_;
	private int maxSize_;
	/**
	 * 
	 * @param maxSize The maximum objects in the queue
	 */
	SynchronizedQueue(int maxSize) {
		maxSize_ = maxSize;
		queue_ = new LinkedList();
	}
	
	/**
	 * Adds object at the end of the queue
	 * @param obj
	 * @throws InterruptedException if the thread is interrupted while waiting to add object
	 */
	public synchronized void enqueue(Object obj) throws InterruptedException {
		while (queue_.size() >= maxSize_) 
			wait();
		queue_.addLast(obj);
		notify();
	}
	
	/**
	 * Returns the first object in the queue 
	 * @return Object 
	 * @throws InterruptedException if the thread is interrupted while waiting to add object
	 */
	public synchronized Object dequeue() throws InterruptedException {
		while (queue_.size() == 0) 
			wait();	
		Object obj = queue_.removeFirst();
		notify();
		return obj;
	}
	
	/**
	 * Used to clear the queue
	 *
	 */
	synchronized void clear() {
		queue_.clear();
		notifyAll();
	}
	/**
	 * 
	 * @return true if the queue is empty
	 */
	boolean isEmpty() {
		return queue_.isEmpty();
	}
	
}
